package com.mvvm.store.ui.delivery;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.viewpager.widget.ViewPager;

import com.leo.utilspro.utils.ToastUtils;
import com.mvvm.store.R;
import com.mvvm.store.base.BaseFragment;
import com.mvvm.store.base.NormalViewModel;
import com.mvvm.store.bean.basebean.DeliveryGetListResultBean;
import com.mvvm.store.bean.basebean.DeliveryInfoBean;
import com.mvvm.store.bean.basebean.MaterialInfoBean;
import com.mvvm.store.bean.basebean.ScanDeliveryBean;
import com.mvvm.store.customview.CustomProgress;
import com.mvvm.store.databinding.FragmentDeliveryInfoBinding;
import com.mvvm.store.databinding.FragmentMaterialInfoBinding;
import com.mvvm.store.roombatabase.DeliveryDatabase;
import com.mvvm.store.roombatabase.DeliveryInfoDao;
import com.mvvm.store.roombatabase.ScanDeliveryDao;
import com.mvvm.store.roombatabase.ScanDeliveryDatabase;
import com.mvvm.store.ui.delivery.adapter.DeliveryInfoAdapter;
import com.mvvm.store.ui.into.adaper.MaterialInfoAdapter;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;


/**
 * Created by leo     MVVM
 * @author  zhouchangyi
 * on 2021/06/15.   出库物料信息界面
 */
public class DeliveryInfoFragment extends BaseFragment<DeliveryViewModel, FragmentDeliveryInfoBinding>{

    int index;
    private DeliveryInfoAdapter infoAdapter;
    private int curPage = 0;
    private ArrayList<DeliveryInfoBean> deliveryInfoBeans = new ArrayList<>();
    private CustomProgress dialog;
    private String id;
    private String stockOrderNo;
    private  DeliveryInfoDao deliveryInfoDao;
    private    List<DeliveryInfoBean> deliveryInfoBeanList;
    private ScanDeliveryDao scanDeliveryDao;

    public static DeliveryInfoFragment newInstance(final String name, ViewPager viewPager) {
        DeliveryInfoFragment mFragment = new DeliveryInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", name);
        mFragment.setArguments(bundle);
        return mFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_delivery_info;
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        handler.postDelayed(runnables, TIME); // 在初始化方法里.
        deliveryInfoDao= DeliveryDatabase.getInstance(getActivity()).deliveryInfoDao();
        scanDeliveryDao= ScanDeliveryDatabase.getInstance(getActivity()).scanDeliveryDao();
        //Sp获取点击出库列表数据的订单号的值
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("deliveryInfo", MODE_PRIVATE);
        id=sharedPreferences.getString("id","");
        stockOrderNo= sharedPreferences.getString("stockOrderNo","");

        System.out.println("orderId---------出库-----------"+id);
        if(dialog==null) {
            dialog = CustomProgress.show(getActivity(), "", true, null);
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(500);//休眠3秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                /**
                 * 要执行的操作
                 */
                dialog.dismiss();
            }
        }.start();
        binding.includeEmpty.setTextEmpty("瞅啥，没有你的收藏~");
        binding.includeEmpty.setImageEmpty(R.mipmap.no_data);

        //根据订单号请求接口获取数据 //---------------------------------
        mViewModel.getDeliveryDetailsList(id).observe(this,resourse->resourse.handler(new OnCallback<DeliveryGetListResultBean>() {
                    @Override
                    public void onSuccess(DeliveryGetListResultBean data) {
                        System.out.println("接口获取数据json"+data.toString());
                        if(data!=null ) {
                            binding.includeEmpty.relativeNull.setVisibility(View.GONE);
                            //将获取到的接口数据设置到对应的控件中  备货
                            binding.tvDeliveryOrderNumber.setText(data.getOutStockOrderNo());
                            binding.tvIntoSupplierName.setText(data.getSupplierName() + "");
                            //查看本地数据库是否有数据 出货
                                //根据订单号和对应的零件号查询本地数据库是否有这条数据 有不管没有就添加到本地数据库中

                            if (data.getNeedCodeList()==null) {
                                Toast.makeText(getActivity(), "未获取到对应的标签信息,请查看系统配置", Toast.LENGTH_SHORT).show();
                            }
                            else {
                                for (int j = 0; j < data.getNeedCodeList().size(); j++) {
                                    System.out.println("--ssssss---------------------------"+data.getNeedCodeList().get(j));
                                    List<ScanDeliveryBean> scanDeliveryBeanList = scanDeliveryDao.getScanDeliveryBeanByLabelNumber(data.getNeedCodeList().get(j));
                                    System.out.println("------scanDeliveryBeanList"+scanDeliveryBeanList.size());
                                 if (scanDeliveryBeanList.size() > 0) {
                                        System.out.println("出库查看到标签表数据存在，不需要参入进去-----------------------------");
                                    }
                                    else {
                                     ScanDeliveryBean scanDeliveryBean = new ScanDeliveryBean();
                                        scanDeliveryBean.setLableNumber(data.getNeedCodeList().get(j));
                                       scanDeliveryBean.setOddNumber("");
                                        scanDeliveryDao.insertAll(scanDeliveryBean);
                                   }
                                }
                            }


                            for (int i=0;i<data.getMaterialList().size();i++){
                                List<DeliveryInfoBean> deliveryInfoBeanListToLoad=  deliveryInfoDao.getDeliveryInfoByOddNumber(stockOrderNo,data.getMaterialList().get(i).getPartNumber());
                                if(deliveryInfoBeanListToLoad.size()>0){
                                    //本地有数据了
                                    System.out.println("出库-------------查询的该订单号对应的零件号本地数据存在了");
                                }else {

                                    System.out.println("出库------------本地数据库没有数据进行添加到本地数据");
                                    //本地数据库不存在进行插入到本地数据库中
                                    DeliveryInfoBean deliveryInfoBean = new DeliveryInfoBean();
                                    deliveryInfoBean.setOrderNumber(data.getOutStockOrderNo());
                                    deliveryInfoBean.setOddNumber(data.getMaterialList().get(i).getPartNumber());
                                    deliveryInfoBean.setSumNumber(Integer.parseInt(data.getMaterialList().get(i).getTotal()));
                                    deliveryInfoBean.setPackNumber(Integer.parseInt(data.getMaterialList().get(i).getBoxCount()));
                                    deliveryInfoBean.setOddName(data.getMaterialList().get(i).getPartName());
                                    deliveryInfoBean.setRealToNumber(0);
                                    deliveryInfoBean.setRealToPack(0);
                                    deliveryInfoBean.setSupplierName(data.getSupplierName());
                                    deliveryInfoBean.setSupplierCode(data.getSupplierCode());
                                    deliveryInfoBean.setAddress("");
                                    deliveryInfoBean.setId(data.getId());
                                    deliveryInfoBean.setOutStockId(data.getMaterialList().get(i).getOutStockId());
                                    deliveryInfoDao.insertAll(deliveryInfoBean);
                                    System.out.println("获取需要参入的标签表数据-----》" + data.getMaterialList().toString());
                                    //到标签表进行参入
                                }
                            }
                            //添加完进行查询刷新适配器
                            deliveryInfoBeanList=  deliveryInfoDao.getDeliveryByOrderNumber(stockOrderNo);
                            for (int i=0;i<deliveryInfoBeanList.size();i++){
                                deliveryInfoBeans.add(deliveryInfoBeanList.get(i));
                            }
                            infoAdapter.notifyDataSetChanged();
                        }else {
                            binding.includeEmpty.relativeNull.setVisibility(View.VISIBLE);
                        }
                    }
                }));

        infoAdapter=new DeliveryInfoAdapter();
        infoAdapter.setDataList(deliveryInfoBeans);
        binding.recyclerView.setAdapter(infoAdapter);


    }

    @Override
    protected void setListener() {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            System.out.println("MaterialInfoFragment----hidden");
        }else {
            System.out.println("MaterialInfoFragment------no----hidden");
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //TODO 刷新数据方法在这里调用
            System.out.println("MaterialInfoFragmentsetUserVisibleHint刷新数据");

            if(infoAdapter!=null && !TextUtils.isEmpty(stockOrderNo)) {
                deliveryInfoBeanList=   deliveryInfoDao.getDeliveryByOrderNumber(stockOrderNo);
                deliveryInfoBeans.clear();
             for (int i=0;i<deliveryInfoBeanList.size();i++){
                 deliveryInfoBeans.add(deliveryInfoBeanList.get(i));
             }
                infoAdapter.notifyDataSetChanged();
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(handler!=null) {
            handler.removeCallbacks(runnables);
        }
    }


    private int TIME = 1000;  //每隔1s执行一次.
    Handler handler = new Handler();

    Runnable runnables=new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, TIME);
            //刷新数据
            // materialInfoBeans.clear();
            // getMaterInforTointent();
            System.out.println("出库扫码监听数据,刷新列表");
            if(infoAdapter!=null && !TextUtils.isEmpty(stockOrderNo)) {
                deliveryInfoBeanList=   deliveryInfoDao.getDeliveryByOrderNumber(stockOrderNo);
                deliveryInfoBeans.clear();
                for (int i=0;i<deliveryInfoBeanList.size();i++){
                    deliveryInfoBeans.add(deliveryInfoBeanList.get(i));
                }
                infoAdapter.notifyDataSetChanged();
            }
        }
    };
}
